// Mandelbrot emits a PNG image of the Mandelbrot fractal.
package main

import (
	"image"
	"image/color"
	"image/png"
	"math/cmplx"
	"os"
)

func main() {
	const (
		xmin, ymin, xmax, ymax = -2, -2, +2, +2
		width, height          = 1024, 1024
		widthp, heightp        = 2048, 2048
	)

	img := image.NewRGBA(image.Rect(0, 0, width, height))
	for py := 0; py < heightp; py++ {
		y := float64(py)/heightp*(ymax-ymin) + ymin
		for px := 0; px < widthp; px++ {
			x := float64(px)/widthp*(xmax-xmin) + xmin
			z := complex(x, y)
			// Image point (px, py) represents complex value z
			img.Set(px/2, py/2, mandelbrot(z))
		}
	}
	png.Encode(os.Stdout, img)
}

func mandelbrot(z complex128) color.Color {
	const iterations = 200
	const contrast = 15

	var v complex128 = 0 + 0i
	for n := uint8(0); n < iterations; n++ {
		v = v*v + z
		if cmplx.Abs(v) > 2 {
			return getColor(contrast, n)
		}
	}
	return color.Black
}

func getColor(contrast uint8, n uint8) color.RGBA {

	return color.RGBA{
		R: 255,
		G: byte(255 - contrast*n),
		B: 255,
		A: 255,
	}
}
